package com.cckat.controller;

import com.cckat.entity.HouseImage;
import com.cckat.result.Result;
import com.cckat.service.HouseImageService;
import com.cckat.utils.QiniuUtil;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * @author 静海基地
 */
@Controller
@RequestMapping("/houseImage")
public class HouseImageController {

    @DubboReference
    private HouseImageService houseImageService;

    @RequestMapping("/uploadShow/{houseId}/{type}")
    public String uploadShow(@PathVariable("houseId") Long houseId, @PathVariable("type") Integer type, Model model){
        model.addAttribute("houseId", houseId);
        model.addAttribute("type", type);
        return "house/upload";
    }


    @RequestMapping("/upload/{houseId}/{type}")
    @ResponseBody
    public Result upload(
            @PathVariable("houseId") Long houseId,
            @PathVariable("type") Integer type,
            @RequestParam(value = "file") MultipartFile[] files
            //使用注解RequestParam有两个作用，其一为请求参数和形参名字一致，若不一致则需要使用注解的value属性进行绑定；
            //其二，若用Map集合获取请求参数，默认为向请求域共享数据的Map集合，加上注解后则为获取请求参数的集合。
            ) throws IOException {
        for (MultipartFile file : files) {
            //获取上传的文件的字节数组
            byte[] bytes = file.getBytes();
            //获取上传文件的文件名
            String fileName = file.getOriginalFilename();
            //获取上传文件的后缀名
            String hzName = fileName.substring(fileName.lastIndexOf("."));
            //获取随机的UUid
            String uuid = UUID.randomUUID().toString();
            //将uuid作为文件上传后的文件名
            fileName = uuid + hzName;
            //将文件上传保存至七牛云
            QiniuUtil.upload2Qiniu(bytes,fileName);

            HouseImage houseImage = new HouseImage();
            houseImage.setHouseId(houseId);
            houseImage.setType(type);
            houseImage.setImageName(fileName);
            houseImage.setImageUrl("http://riyf343zt.hn-bkt.clouddn.com/"+fileName);
            houseImageService.insert(houseImage);
        }
        return Result.ok();
    }


    @RequestMapping("/delete/{houseId}/{id}")
    public String delete(@PathVariable("houseId") Long houseId, @PathVariable("id") Long id, Model model){
        HouseImage houseImage = houseImageService.getById(id);
        QiniuUtil.deleteFileFromQiniu(houseImage.getImageName());
        houseImageService.delete(id);
        return "redirect:/house/"+houseId;
    }

}
